using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

using System.Web;
using System.IO;

namespace Pampa.Common.HTTPHandlers
{
    public abstract class BaseHandler : IHttpHandler
    {
        private string path;
        protected string contentType;
        protected string fileType;

        public BaseHandler(string path) : this(path, "text/plain") {} 

        public BaseHandler(string path, string contentType)
        {
            this.path = path;
            this.contentType = contentType;
        }
        
        bool IHttpHandler.IsReusable
        {
            get { return true; }
        }

        /// <summary>
        ///  Root/FrameworkName/FileName
        /// </summary>
        /// <param name="context"></param>
        void IHttpHandler.ProcessRequest(HttpContext context)
        {
            string absolutePath = context.Request.Url.AbsolutePath;
            int pampaStart = absolutePath.LastIndexOf("Pampa");
            string relativePath = absolutePath.Substring(pampaStart, absolutePath.Length - pampaStart);

            relativePath = relativePath.Replace("/", ".");

            string assemblyName = relativePath.Split('.')[0] + "." + relativePath.Split('.')[1];
            string filePath = relativePath.Replace(assemblyName, "").Substring(1);

            /*
            int lastSlash = url.LastIndexOf('/') + 1;
            string assemblyName = url.Substring(startAssemblyName, lastSlash - startAssemblyName - 1);
            string fileName = url.Substring(lastSlash, url.Length - lastSlash);
            */

            Assembly assembly = Assembly.Load(new AssemblyName(assemblyName));
            string fileFullName = string.Format(assemblyName + ".UI." + path + ".{0}", filePath);
            Stream stream = assembly.GetManifestResourceStream(fileFullName);

            if(stream!=null)
                WriteContent(context, stream, fileFullName);
        }

        protected virtual void WriteContent(HttpContext context, Stream stream, string fileName)
        {
            try
            {
                string content = string.Empty;
                using (System.IO.StreamReader sr = new System.IO.StreamReader(stream))
                {
                    content = sr.ReadToEnd();
                }

                context.Response.Clear();
                context.Response.ContentType = this.contentType;
                context.Response.ContentEncoding = new System.Text.UTF8Encoding();
                context.Response.Write(content);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
            }

            context.Response.End();        
        }
    }
}
